var http = require('../../../../script/api.js');
var config = require('../../../../script/config.js')
var context = null; // 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false; //是否在绘制中
var arrx = []; //动作横坐标
var arry = []; //动作纵坐标
var arrz = []; //总做状态，标识按下到抬起的一个组合
var canvasw = 0; //画布宽度
var canvash = 0; //画布高度

Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    orderinfo: {
      type: Object,
      value: null
    },
  },
  observers: {
    'orderinfo': function (val) {
      if (val != null) {
        this.setDefaultValue();
        // this.GetComplainCount();
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    TempTimeIndex: 0,
    TempTimeList: ['9:00 - 11:00', '15:00 - 18:00', '18:00之后', '其他时段'],
    time: '12:01',
    ProcHandReasonList: [],
    SolveWayList: [],
    SubmitData: {
      ProcHandReason: '',
      OTHERREASON: '',
      SOLVEWAY: '',
      SOLVEREMARK: '',
      LineType: null,
      DeviceType: null,
      Orientation: '',
      TempPeriod: '9:00 - 11:00',
      TempPeriodStart: '00:00',
      TempPeriodEnd: '00:00',
      RoomSeal: 1,
      DeviceSeal: 1,
      DeviceModify: 0,
      OutConnect: 0,
      BedroomTemp: null,
      BedroomTemp2: null,
      BedroomTemp3: null,
      LivingRoomTemp: null,
      AvgTemp: null,
      SignUrl: ''
      // BeginTime: '',
      // EndTime: '',
      // HeatSide1Temp: null,
      // HeatSide1BackTemp: null,
      // HeatSide2Temp: null,
      // HeatSide2BackTemp: null,
      // OuterTemp: null,
      // DeviceTemp: null,
      // LivingRoomTemp: null,
      // BedroomTemp: null,
      // SupplyTemp: null,
      // ReturnTemp: null,
      // NormalFlag: '0',
      // PetitionFlag: '0',
      // ACCUMBACKFEEDAYS: null,
      // COMPLAINCOUNT: null,
    },
    /********电子签名相关********/
    signUrl: '', // 签名本地地址
    signSurl: '', // 签名上传服务器地址
    signBase64: '',
    sysType: '', // 判断机型
    // showSign: false,
    baseUrl: config.baseUrl,
    /********电子签名相关********/
  },
  lifetimes: {
    attached() {
      this.getList('ProcHandReason');
      this.getList('SolveWay');

      /********电子签名 *********/
      let that = this
      let res = wx.getSystemInfoSync()
      const system = res.system.split(' ')
      that.setData({
        sysType: system[0],
      })
      that.startCanvas();
      that.initCanvas();
      /********电子签名 *********/
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getList(type) {
      http.GetPCodeList({
        CODE_TYPE: type,
      }).then(res => {
        if (res.code === 200) {
          const resData = res.data || [];
          const list = resData.find(item => item.VALUE === '004');
          if (list) {
            const children = [...list.Childrens];
            children.push({
              NAME: '其他',
              VALUE: '099'
            });
            if (type === 'ProcHandReason') {
              this.setData({
                ProcHandReasonList: children,
              });
            } else if (type === 'SolveWay') {
              this.setData({
                SolveWayList: children,
              });
            }
          }
        }
      });
    },
    // GetComplainCount() {
    //   http.GetComplainCount({
    //     ConsNo: this.data.orderinfo.ConsNo
    //   }).then(res => {
    //     if (res.code === 200) {
    //       this.setData({
    //         "SubmitData.COMPLAINCOUNT": res.data ? res.data.ComplainCount : null
    //       });
    //     }
    //   })
    // },
    setDefaultValue() {
      this.setData({
        // "SubmitData.SOLVEWAY": this.data.orderinfo.SolveWay,
        // "SubmitData.SOLVEREMARK": this.data.orderinfo.SolveRemark,
        "SubmitData.ProcHandReason": this.data.orderinfo.ProcHandReason,
        "SubmitData.OTHERREASON": this.data.orderinfo.OtherReason,
        // "SubmitData.NormalFlag": this.data.orderinfo.NormalFlag == null ? '0' : this.data.orderinfo.NormalFlag,
        // "SubmitData.PetitionFlag": this.data.orderinfo.PetitionFlag == null ? '0' : this.data.orderinfo.PetitionFlag
      });
      const WorkOrderTempInfo = this.data.orderinfo.WorkOrderTempInfo;
      if (WorkOrderTempInfo) {
        let TempPeriod = WorkOrderTempInfo.TempPeriod;
        let TempPeriodStart = '00:00';
        let TempPeriodEnd = '00:00';
        let index = this.data.TempTimeList.findIndex(item => item === TempPeriod);
        if (index === -1) {
          TempPeriodStart = TempPeriod.split('-')[0];
          TempPeriodEnd = TempPeriod.split('-')[1];
          index = 3;
          TempPeriod = '其他时段';
        }
        this.setData({
          // "SubmitData.BeginTime": WorkOrderTempInfo.BeginTime,
          // "SubmitData.EndTime": WorkOrderTempInfo.EndTime,
          "SubmitData.LineType": WorkOrderTempInfo.LineType,
          "SubmitData.DeviceType": WorkOrderTempInfo.DeviceType,
          "SubmitData.Orientation": WorkOrderTempInfo.Orientation,
          "SubmitData.RoomSeal": WorkOrderTempInfo.RoomSeal,
          "SubmitData.DeviceSeal": WorkOrderTempInfo.DeviceSeal,
          "SubmitData.DeviceModify": WorkOrderTempInfo.DeviceModify,
          "SubmitData.OutConnect": WorkOrderTempInfo.OutConnect,
          "SubmitData.BedroomTemp": WorkOrderTempInfo.BedroomTemp,
          "SubmitData.BedroomTemp2": WorkOrderTempInfo.BedroomTemp2,
          "SubmitData.BedroomTemp3": WorkOrderTempInfo.BedroomTemp3,
          "SubmitData.SignUrl": WorkOrderTempInfo.UserSign != null ? this.data.baseUrl + '/' + WorkOrderTempInfo.UserSign.FilePath : '',
          "SubmitData.LivingRoomTemp": WorkOrderTempInfo.LivingRoomTemp,
          "SubmitData.AvgTemp": WorkOrderTempInfo.AvgTemp,
          "SubmitData.TempPeriod": TempPeriod,
          "SubmitData.TempPeriodStart": TempPeriodStart,
          "SubmitData.TempPeriodEnd": TempPeriodEnd,
          TempTimeIndex: index
        });
      }
      // if (this.data.orderinfo.WeatherInfo) {
      //   this.setData({
      //     "SubmitData.OuterTemp": this.data.orderinfo.WeatherInfo.Temperature
      //   });
      // }
    },
    /*********************测温************* */
    TempTimeChange(e) {
      const index = parseInt(e.detail.value);
      this.setData({
        TempTimeIndex: index,
        "SubmitData.TempPeriod": this.data.TempTimeList[index]
      })
      if (index != 3) {
        this.setData({
          "SubmitData.TempPeriodStart": '00:00',
          "SubmitData.TempPeriodEnd": '00:00'
        })
      }
    },
    TempTimeStartChange(e) {
      this.setData({
        "SubmitData.TempPeriodStart": e.detail.value
      })
    },
    TempTimeEndChange(e) {
      this.setData({
        "SubmitData.TempPeriodEnd": e.detail.value
      })
    },
    formChange(e) {
      const type = e.currentTarget.dataset.type;
      this.setData({
        ["SubmitData." + type]: e.detail.value
      });
    },
    tempChange: function (e) {
      const type = e.currentTarget.dataset.type;
      let val = e.detail.value
      val = val.replace(/[^\d.-]/g, ""); //清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      this.setData({
        ["SubmitData." + type]: val
      });
    },
    /*********************测温************* */
    /*********************电子签名************* */
    //画布初始化执行
    startCanvas() {
      var that = this;
      wx.getSystemInfo({
        success: function (res) {
          canvasw = res.windowWidth;
          canvash = res.windowHeight;
          // that.setData({
          //   canvasw: canvasw,
          //   canvash: canvash
          // });
        }
      });
      this.initCanvas();
      this.cleardraw();
    },
    //初始化函数
    initCanvas() {
      context = wx.createCanvasContext('canvas', this);
      context.beginPath()
      if (this.data.sysType === 'iOS') {
        context.fillStyle = 'rgba(255, 255, 255, 1)';
        context.setStrokeStyle('#444');
      } else {
        context.fillStyle = 'rgba(0, 0, 0, 1)';
        context.setStrokeStyle('#aaa');
      }
      context.setLineWidth(4);
      context.setLineCap('round');
      context.setLineJoin('round');
    },
    canvasStart(event) {
      isButtonDown = true;
      arrz.push(0);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    },
    canvasMove(event) {
      if (isButtonDown) {
        arrz.push(1);
        arrx.push(event.changedTouches[0].x);
        arry.push(event.changedTouches[0].y);
      }
      for (var i = 0; i < arrx.length; i++) {
        if (arrz[i] == 0) {
          context.moveTo(arrx[i], arry[i])
        } else {
          context.lineTo(arrx[i], arry[i])
        }
      }
      context.clearRect(0, 0, canvasw, canvash);
      if (this.data.sysType === 'iOS') {
        context.fillStyle = 'rgba(255, 255, 255, 1)';
        context.setStrokeStyle('#444');
      } else {
        context.fillStyle = 'rgba(0, 0, 0, 1)';
        context.setStrokeStyle('#aaa');
      }
      context.setLineWidth(3);
      context.setLineCap('round');
      context.setLineJoin('round');
      context.stroke();
      context.draw(false);
    },
    canvasEnd(event) {
      isButtonDown = false;
    },
    //清除画布
    cleardraw(e) {
      arrx = [];
      arry = [];
      arrz = [];
      context.clearRect(0, 0, canvasw, canvash);
      if (this.data.sysType === 'iOS') {
        context.fillStyle = 'rgba(255, 255, 255, 1)';
        context.setStrokeStyle('#444');
      } else {
        context.fillStyle = 'rgba(0, 0, 0, 1)';
        context.setStrokeStyle('#aaa');
      }
      context.draw(true);
      if (e) {
        this.setData({
          "SubmitData.SignUrl": ''
        });
      }

    },
    uploadImg() {
      if (arrx.length === 0) {
        wx.showToast({
          title: '请先签名！',
          icon: 'error',
          duration: 2000
        })
        return
      }
      var that = this
      wx.showLoading({
        mask: true,
        title: '签名上传中...'
      });
      //生成图片
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'canvas',
          //设置输出图片的宽高
          fileType: 'jpg',
          quality: 1,
          success: function (res) {
            // canvas图片地址 res.tempFilePath
            let imgBase64 = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
            that.setData({
              signUrl: res.tempFilePath,
              signBase64: imgBase64
            })
            that.uploadSignImg(res.tempFilePath)
          },
          fail: function (err) {
            wx.showModal({
              title: '提示',
              content: 'canvas生成图片失败。微信当前版本不支持，请更新到最新版本！',
              showCancel: false
            });
          },
          complete: function () {

          }
        }, that)
      }, 3000)
    },
    uploadSignImg(path) {
      const token = wx.getStorageSync(config.storageKey.token)
      const xtoken = wx.getStorageSync(config.storageKey.xtoken)
      wx.uploadFile({
        url: config.baseUrl + '/api/Upload/Upload',
        method: "POST",
        header: {
          'Authorization': 'Bearer ' + token,
          'X-Authorization': 'Bearer ' + xtoken
        },
        filePath: path,
        name: 'file',
        success: (resf) => {
          if (resf.statusCode === 200) {
            // const resData = JSON.parse(resf.data).data;
            const resData = JSON.parse(resf.data);
            if (resData.code === 200) {
              this.setData({
                signSurl: resData.data[0]
              })
              wx.showToast({
                title: '上传签名成功！',
                icon: "none",
                duration: 2000
              })
            } else {
              wx.showToast({
                title: '上传签名失败！',
                icon: "none",
                duration: 2000
              });
            }
          } else {
            wx.showToast({
              title: '上传签名失败！',
              icon: "none",
              duration: 2000
            });
          }
        }
      })
    },
    /*********************电子签名************* */
    getSubmitData(isCheck = true) {
      if (isCheck) {
        // if (this.data.SubmitData.SOLVEWAY == null || this.data.SubmitData.SOLVEWAY == '') {
        //   wx.showToast({
        //     title: '解决措施不能为空！',
        //     icon: 'none',
        //     duration: 2000
        //   });
        //   return null;
        // } else {
        //   if (this.data.SubmitData.SOLVEWAY === '099') {
        //     if (this.data.SubmitData.SOLVEREMARK == null || this.data.SubmitData.SOLVEREMARK == '') {
        //       wx.showToast({
        //         title: '其他措施文字说明不能为空！',
        //         icon: 'none',
        //         duration: 2000
        //       });
        //       return null;
        //     }
        //   }
        // }
        if (this.data.SubmitData.ProcHandReason == null || this.data.SubmitData.ProcHandReason == '') {
          wx.showToast({
            title: '不热原因不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        } else {
          if (this.data.SubmitData.ProcHandReason === '099') {
            if (this.data.SubmitData.OTHERREASON == null || this.data.SubmitData.OTHERREASON == '') {
              wx.showToast({
                title: '其他原因文字说明不能为空！',
                icon: 'none',
                duration: 2000
              });
              return null;
            }
          }
        }
      }
      const submitData = {
        ProcHandReason: this.data.SubmitData.ProcHandReason,
        OTHERREASON: this.data.SubmitData.OTHERREASON,
        // SOLVEWAY: this.data.SubmitData.SOLVEWAY,
        // SOLVEREMARK: this.data.SubmitData.SOLVEREMARK,
      }
      if (isCheck) {
        if (this.data.SubmitData.LineType == null) {
          wx.showToast({
            title: '请选择庭院管网结构！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.DeviceType == null) {
          wx.showToast({
            title: '请选择散热设备！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.TempTimeIndex == 3 && (this.data.SubmitData.TempPeriodStart === '' || this.data.SubmitData.TempPeriodEnd === '')) {
          wx.showToast({
            title: '请完善测温时段！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }

        if (this.data.SubmitData.BedroomTemp == null || this.data.SubmitData.BedroomTemp === '') {
          wx.showToast({
            title: '卧室1温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        } else if ((this.data.SubmitData.BedroomTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.BedroomTemp))) {
          wx.showToast({
            title: '卧室1温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        // if (this.data.SubmitData.BedroomTemp2 == null || this.data.SubmitData.BedroomTemp2 === '') {
        //   wx.showToast({
        //     title: '卧室2温度不能为空！',
        //     icon: 'none',
        //     duration: 2000
        //   });
        //   return null;
        // } else if ((this.data.SubmitData.BedroomTemp2 + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.BedroomTemp2))) {
        //   wx.showToast({
        //     title: '卧室2温度格式不正确！',
        //     icon: 'none',
        //     duration: 2000
        //   });
        //   return null;
        // }
        // if (this.data.SubmitData.BedroomTemp3 == null || this.data.SubmitData.BedroomTemp3 === '') {
        //   wx.showToast({
        //     title: '卧室3温度不能为空！',
        //     icon: 'none',
        //     duration: 2000
        //   });
        //   return null;
        // } else if ((this.data.SubmitData.BedroomTemp3 + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.BedroomTemp3))) {
        //   wx.showToast({
        //     title: '卧室3温度格式不正确！',
        //     icon: 'none',
        //     duration: 2000
        //   });
        //   return null;
        // }
        if (this.data.SubmitData.LivingRoomTemp == null || this.data.SubmitData.LivingRoomTemp === '') {
          wx.showToast({
            title: '方厅温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        } else if ((this.data.SubmitData.LivingRoomTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.LivingRoomTemp))) {
          wx.showToast({
            title: '方厅温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.AvgTemp == null || this.data.SubmitData.AvgTemp === '') {
          wx.showToast({
            title: '平均温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        } else if ((this.data.SubmitData.AvgTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.AvgTemp))) {
          wx.showToast({
            title: '平均温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
      }
      submitData.WorkOrderTempInfo = {
        // BeginTime: this.data.SubmitData.BeginTime,
        // EndTime: this.data.SubmitData.EndTime,
        LineType: this.data.SubmitData.LineType,
        DeviceType: this.data.SubmitData.DeviceType,
        Orientation: this.data.SubmitData.Orientation,
        TempPeriod: this.data.TempTimeIndex == 3 ? this.data.SubmitData.TempPeriodStart + '-' + this.data.SubmitData.TempPeriodEnd : this.data.SubmitData.TempPeriod,
        RoomSeal: this.data.SubmitData.RoomSeal,
        DeviceSeal: this.data.SubmitData.DeviceSeal,
        DeviceModify: this.data.SubmitData.DeviceModify,
        OutConnect: this.data.SubmitData.OutConnect,
        BedroomTemp: this.data.SubmitData.BedroomTemp ? parseFloat(this.data.SubmitData.BedroomTemp) : null,
        BedroomTemp2: this.data.SubmitData.BedroomTemp2 ? parseFloat(this.data.SubmitData.BedroomTemp2) : null,
        BedroomTemp3: this.data.SubmitData.BedroomTemp3 ? parseFloat(this.data.SubmitData.BedroomTemp3) : null,
        LivingRoomTemp: this.data.SubmitData.LivingRoomTemp ? parseFloat(this.data.SubmitData.LivingRoomTemp) : null,
        AvgTemp: this.data.SubmitData.AvgTemp ? parseFloat(this.data.SubmitData.AvgTemp) : null,
        // DeviceTemp: this.data.SubmitData.DeviceTemp ? parseFloat(this.data.SubmitData.DeviceTemp) : null,
        // LivingRoomTemp: this.data.SubmitData.LivingRoomTemp ? parseFloat(this.data.SubmitData.LivingRoomTemp) : null,
        // BedroomTemp: this.data.SubmitData.BedroomTemp ? parseFloat(this.data.SubmitData.BedroomTemp) : null,
        // SupplyTemp: this.data.SubmitData.SupplyTemp ? parseFloat(this.data.SubmitData.SupplyTemp) : null,
        // ReturnTemp: this.data.SubmitData.ReturnTemp ? parseFloat(this.data.SubmitData.ReturnTemp) : null,
        // ACCUMBACKFEEDAYS: this.data.SubmitData.ACCUMBACKFEEDAYS,
        // COMPLAINCOUNT: this.data.SubmitData.COMPLAINCOUNT,
      }
      if (isCheck) {
        if (this.data.orderinfo.WorkOrderTempInfo && this.data.orderinfo.WorkOrderTempInfo.UserSign) {
          // 已经签过，可以重新签名，也可以不签名
          if (this.data.signSurl !== "") {
            submitData.WorkOrderTempInfo.UserSign = {
              FileName: 'sign',
              FilePath: this.data.signSurl,
              Size: 200
            }
          }
        } else {
          if (this.data.signSurl === "") {
            wx.showToast({
              title: '请上传客户签字！',
              icon: 'none',
              duration: 2000
            });
            return null;
          }
          submitData.WorkOrderTempInfo.UserSign = {
            FileName: 'sign',
            FilePath: this.data.signSurl,
            Size: 200
          }
        }
      } else {
        submitData.WorkOrderTempInfo.UserSign = {
          FileName: 'sign',
          FilePath: this.data.signSurl,
          Size: 200
        }
      }
      return submitData;
    },
  }
})